/*
 * @Author: yangy
 * @Date: 2023-12-14 15:41:28
 * @LastEditors: yangy
 * @LastEditTime: 2023-12-20 16:11:11
 * @FilePath: /admin_vue3_element_plus/src/store/index.js
 * @Description:
 *
 * Copyright (c) 2023 by 青柠利合科技(北京)有限公司, All Rights Reserved.
 */
import { createStore } from "vuex";
import { getInfo, login } from "@/api/manager";
import { setToken, removeToken } from "../utils/auth";
const store = createStore({
  state() {
    return {
      // 用户信息
      user: {},
      // 侧边宽度
      asideWidth: "250px",
      //菜单
      menus: [],
      ruleNames: [],
    };
  },
  mutations: {
    // 记录用户信息
    SET_USERINFO(state, user) {
      state.user = user;
    },
    // 展开或者收起侧边栏
    handleAsideWidth(state) {
      state.asideWidth = state.asideWidth == "250px" ? "64px" : "250px";
    },
    // 设置菜单
    SET_MENUS(state, menus) {
      state.menus = menus;
    },
    SET_RULENAMES(state, ruleNames) {
      state.ruleNames = ruleNames;
    },
  },
  actions: {
    // 登录
    login({ commit }, { username, password }) {
      return new Promise((resolve, reject) => {
        login(username, password)
          .then((res) => {
            setToken(res.data.token);
            resolve();
          })
          .catch((err) => reject(err));
      });
    },
    // 获取当前用户登录信息
    getInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            // 获取用户信息 并存储到vuex中
            commit("SET_USERINFO", res);
            commit("SET_MENUS", res.data.menus);
            commit("SET_RULENAMES", res.data.ruleNames);
            resolve(res.data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    // 退出登录
    logout({ commit }) {
      // 移除cookie里的token
      removeToken();
      //清除当前用户状态 vuex
      commit("SET_USERINFO", {});
      // location.reload(); // 为了重新实例化vue-router对象 避免bug
      // return Promise.resolve();
    },
  },
});

export default store;
